package com.the_ring.chapter06;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.the_ring.chapter06.adapter.CartItemAdapter;
import com.the_ring.chapter06.bean.GoodsInfo;
import com.the_ring.chapter06.databse.DatabaseHelper;
import com.the_ring.chapter06.util.FileUtil;
import com.the_ring.chapter06.util.ShareUtil;

import java.util.List;

public class ShoppingCartActivity extends AppCompatActivity implements View.OnClickListener {

    private String isFirst = "true";

    private ImageView backIv;
    private TextView titleTv;
    private ImageView cartIv;
    private TextView countTv;
    private RelativeLayout cartListRl;
    private ListView shopCartLv;
    private Button clearBt;
    private TextView totalMoneyTv;
    private Button checkBt;
    private LinearLayout cartEmptyLl;
    private Button goShopBt;

    private List<GoodsInfo> infoList;
    private CartItemAdapter cartItemAdapter;


    private DatabaseHelper helper;

    private int carCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_cart);

        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        helper = DatabaseHelper.getInstance(this);
        helper.openWriteLink();

        initData();
    }

    @Override
    protected void onPause() {
        super.onPause();
        helper.closeLink();
    }

    public void initView() {
        backIv = findViewById(R.id.iv_back);
        titleTv = findViewById(R.id.tv_title);
        cartIv = findViewById(R.id.iv_shop);
        countTv = findViewById(R.id.tv_count);
        cartListRl = findViewById(R.id.rl_shopping_cart);
        shopCartLv = findViewById(R.id.lv_shop_cart);
        clearBt = findViewById(R.id.bt_clear);
        totalMoneyTv = findViewById(R.id.tv_total_money);
        checkBt = findViewById(R.id.bt_check);
        cartEmptyLl = findViewById(R.id.ll_empty);
        goShopBt = findViewById(R.id.bt_go_shopping);

        backIv.setOnClickListener(this);
        cartIv.setOnClickListener(this);
        clearBt.setOnClickListener(this);
        checkBt.setOnClickListener(this);
        goShopBt.setOnClickListener(this);
    }

    public void initData() {
        downLoadGoods();

        titleTv.setText("购物车");
        carCount = helper.countOfCart();
        if (carCount > 0) {
            cartListRl.setVisibility(View.VISIBLE);
            cartEmptyLl.setVisibility(View.GONE);
        } else {
            cartListRl.setVisibility(View.GONE);
            cartEmptyLl.setVisibility(View.VISIBLE);
        }
        countTv.setText(String.valueOf(carCount));

        infoList = helper.queryCarList();
        cartItemAdapter = new CartItemAdapter(this, infoList);
        shopCartLv.setAdapter(cartItemAdapter);

        float totalMoney = 0;
        for (GoodsInfo info : infoList) {
            totalMoney += info.num * info.price;
        }
        totalMoneyTv.setText(String.valueOf(totalMoney));
    }

    // 模拟网络数据，初始化数据库中的商品信息
    private void downLoadGoods() {
        isFirst = ShareUtil.getInstance(this).readString("first", "true");
        // 获取当前 App 的私有下载地址
        String path = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString() + "/";
        if (isFirst.equals("true")) {   // 如果是首次打开
            // 模拟图片下载
            List<GoodsInfo> goodsInfoList = GoodsInfo.getDefaultList();
            for (int i = 0; i < goodsInfoList.size(); i++) {
                GoodsInfo info = goodsInfoList.get(i);
                // 网商品数据库中插入一条该商品的记录
                long rowId = helper.insert(info);
                info.rowId = rowId;
                Bitmap pic = BitmapFactory.decodeResource(getResources(), info.pic);
                String pic_path = path + rowId + ".jpg";
                FileUtil.saveImage(pic_path, pic);      // 往存储卡中保存商品图片
                pic.recycle();
                info.picPath = pic_path;
                helper.update(info);
            }
        }
        ShareUtil.getInstance(this).writeString("first", "false");
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.iv_shop) {
            Intent intent = new Intent(this, ShoppingChannelActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        } else if (id == R.id.bt_clear) {
            helper.clearCart();
            carCount = 0;
            countTv.setText("0");
            infoList.clear();
            cartItemAdapter.notifyDataSetChanged();
            cartListRl.setVisibility(View.GONE);
            cartEmptyLl.setVisibility(View.VISIBLE);
        } else if (id == R.id.bt_check) {
            helper.clearCart();
            carCount = 0;
            countTv.setText("0");
            infoList.clear();
            cartItemAdapter.notifyDataSetChanged();
            cartListRl.setVisibility(View.GONE);
            cartEmptyLl.setVisibility(View.VISIBLE);
        } else if (id == R.id.bt_go_shopping) {
            Intent intent = new Intent(this, ShoppingChannelActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
    }
}